package me.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import me.domain.Admin;
import me.service.AdminService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 用于登陆的controller
 *
 * @author Rainh
 */

@Controller
public class AdminController {

    //实例化adminService对象
//    private AdminService adminService = new AdminServiceImpl();

    @Resource(name = "adminService")
    private AdminService adminService;

    @RequestMapping(value = "/loginController")
    public String login(Admin admin, HttpSession session)  {

        //判断用户名和密码是否存在
        boolean exist = adminService.exist(admin);
        if(!exist){
            //如果不存在
//            request.getRequestDispatcher("error.jsp").forward(request,response);
            return "forward:error.jsp";
        }else{
            //如果存在，保存登陆信息
            session.setAttribute("ADMIN_PERMISSION",admin);
            //转发到首页
//            request.getRequestDispatcher("/indexController").forward(request,response);

            return "forward:indexController";
        }
//        return;

    }


    @RequestMapping(value = "/ajaxLoginController")
    public @ResponseBody void ajaxLogin(@RequestBody Admin admin, HttpServletResponse response, HttpSession session) throws IOException {

        //判断是否存在
        boolean exist = adminService.exist(admin);

        if(!exist){
            //如果存在，保存登陆信息
            session.setAttribute("ADMIN_PERMISSION",admin);
        }

        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(exist);
            //如果不存在，回调函数
        //写入到前台
        response.setContentType("application/json;charset=UTF-8");
        //将json写入前台
        response.getWriter().write(json);
        return;
    }

    /**
     * 退出登陆的时候
     * @param session
     * @return
     */
    @RequestMapping(value = "/exitLoginController")
    public String exitLoginController(HttpSession session){

        //注销登录信息
        session.removeAttribute("ADMIN_PERMISSION");
        //返回登录页面
        return "login";
    }
}
